package cc.shacocloud.mirage.context.restful;

import cc.shacocloud.mirage.restful.VertxRouterDispatcherHandler;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.http.HttpServer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Objects;

/**
 * 基于 vertx 核心机制，将web服务部署成一个站点
 */
public class MirageWebServerVerticle extends AbstractVerticle {
    
    private final MirageWebServerOptions mirageWebServerOptions;
    
    @Nullable
    private HttpServer httpServer;
    
    public MirageWebServerVerticle(MirageWebServerOptions mirageWebServerOptions) {
        this.mirageWebServerOptions = mirageWebServerOptions;
    }
    
    @Override
    public void start(@NotNull Promise<Void> startPromise) {
        VertxRouterDispatcherHandler.createHttpServer(vertx, mirageWebServerOptions)
                .onFailure(startPromise::fail)
                .onSuccess(httpServer -> {
                    this.httpServer = httpServer;
                    startPromise.complete();
                });
        
    }
    
    @Override
    public void stop(Promise<Void> stopPromise) {
        if (Objects.nonNull(httpServer)) {
            httpServer.close().onFailure(stopPromise::fail)
                    .onSuccess(httpServer -> stopPromise.complete());
        } else {
            stopPromise.complete();
        }
    }
}
